<template>
  <div id="MyHome"></div>
	<div @click="exportBtn" style="position: fixed;top: 10px;left: 10px;color: #fff;z-index: 999;cursor: pointer;">导出GLB</div>
</template>

<script setup>
	import { onMounted } from 'vue'
	import * as THREE from 'three'
	import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
	import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter.js';

	// 创建场景
	const scene = new THREE.Scene();

	onMounted(() => {
		init(scene)
	})

	const init = (scene) => {
		const container = document.getElementById('MyHome');

		// 创建相机
		const camera = new THREE.PerspectiveCamera(
			75,
			container.offsetWidth / container.offsetHeight,
			0.1,
			1000
		);
		camera.position.z = 5;
    camera.position.x = 2;
    camera.position.y = 2;
    camera.lookAt(0, 0, 0);

		// 创建渲染器
		const renderer = new THREE.WebGLRenderer();
		renderer.setSize(container.offsetWidth, container.offsetHeight);
		container.appendChild(renderer.domElement);

		// 创建一个立方体
		const geometry = new THREE.BoxGeometry(1, 1, 1);
		const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
		const cube = new THREE.Mesh(geometry, material);
		scene.add(cube);

    // 添加坐标辅助器
    const axesHelper = new THREE.AxesHelper(5)
    scene.add(axesHelper);

		// 添加轨道控制器
		const controls = new OrbitControls(camera, renderer.domElement);
    // 设置带阻尼的惯性
    controls.enableDamping = true;
    controls.dampingFactor = 0.01;
    controls.autoRotate = true;


		// 动画函数
		const animate = () => {
			requestAnimationFrame(animate);

			// 旋转立方体
			// cube.rotation.x += 0.01;
			// cube.rotation.y += 0.01;

			renderer.render(scene, camera);
		};

		animate();

		// 处理窗口大小变化
		window.addEventListener('resize', () => {
			const width = container.offsetWidth;
			const height = container.offsetHeight;
			renderer.setSize(width, height);
			camera.aspect = width / height;
			camera.updateProjectionMatrix();
		});
	}

	const exportGLB = (scene, type = 'glb') => {
		const exporter = new GLTFExporter();
		const options = {
			trs: true,      // 是否保留位置、旋转、缩放信息
			// animations: this.modelAnimation, // 导出的动画
			binary: type == 'glb' ? true : false,  // 是否以二进制格式输出
			embedImages: true,//是否嵌入贴图
			onlyVisible: true, //是否只导出可见物体
			forcePowerOfTwoTextures: true,
			includeCustomMaterials: true, //指定是否包含自定义材质
			includeCustomAttributes: true, //	指定是否包含自定义属性
			includeCustomTextures: true, //	指定是否包含自定义纹理
			includeCustomSamplers: true, //	指定是否包含自定义采样器
			includeCustomImages: true, //	指定是否包含自定义图像
			includeCustomTechniques: true, //	指定是否包含自定义技术
			includeCustomMaterialsCommon: true, //指定是否包含自定义 MaterialsCommon
			includeCustomMeshes: true,//指定是否包含自定义网格
			includeCustomSkins: true, //指定是否包含自定义皮肤
			includeCustomNodes: true, // 指定是否包含自定义节点
			includeCustomGeometries: true, //指定是否包含自定义几何体
			includeCustomPrograms: true, // 指定是否包含自定义程序
			includeCustomShaders: true, //指定是否包含自定义着色器
			includeCustomExtensions: true, //指定是否包含自定义扩展。如果设置为true，则会包含在导出中定义的自定义GLTF扩展
		}

		exporter.parse(
			scene,
			(gltf) => {
				console.log('GLTF data:', gltf); // 调试输出GLTF数据
				if (gltf instanceof ArrayBuffer) {
					saveArrayBuffer(gltf, `${new Date().toLocaleString()}.glb`);
				} else {
					console.error('不是 ArrayBuffer 数据');
				}
			},
			(error) => {
				console.error('Error exporting GLB:', error);
			},
			options
		);
	}
	function saveArrayBuffer(buffer, filename) {
		// 将二进制数据保存为文件
		const blob = new Blob([buffer], { type: 'application/octet-stream' });
		const url = URL.createObjectURL(blob);
		const link = document.createElement('a');
		link.href = url;
		link.download = filename;
		link.click();
		URL.revokeObjectURL(url);
		console.log('导出成功')
	}

	const exportBtn = () => {
		exportGLB(scene)
	}


</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
	#MyHome {
		width: 100%;
		height: 100%;
	}
</style>
